<?php

namespace App\Containers\AppSection\Qualification\UI\API\Requests;

use App\Containers\AppSection\Ban\Traits\ProfilesBan;
use App\Containers\AppSection\Ban\Traits\UsersBan;
use App\Containers\AppSection\File\Tasks\FindFileByIdTask;
use App\Containers\AppSection\Settings\Tasks\FindSettingByKeyTask;
use App\Ship\Parents\Requests\Request;
use App\Ship\Traits\AccreditationStatusPermissionTrait;
use Illuminate\Validation\Rule;

class SendToQualificationRequest extends Request
{
    use AccreditationStatusPermissionTrait;
    use ProfilesBan;
    use UsersBan;

    /**
     * Define which Roles and/or Permissions has access to this request.
     */
    protected array $access = [
        'permissions' => '',
        'roles' => 'investor',
    ];

    /**
     * Id's that needs decoding before applying the validation rules.
     */
    protected array $decode = [
        // 'id',
    ];

    /**
     * Defining the URL parameters (e.g, `/user/{id}`) allows applying
     * validation rules on them and allows accessing them like request data.
     */
    protected array $urlParameters = [
        // 'id',
    ];

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'code' => ['required', 'digits:' . config('appSection-confirmation.code-length')],
            'guarantee' => ['required'],
            'guarantee.selected' => ['required', Rule::in([true])],
            'conditions' => ['required', 'array', function ($attribute, $value, $fail) {
                $conditions = app(FindSettingByKeyTask::class)->run('qualification_conditions');
                $selected = 0;
                foreach ($conditions->value['conditions'] as $key => $condition) {
                    if (!isset($value[$key]['text']) || strcmp(trim($condition['text']), trim($value[$key]['text'])) !== 0) {
                        $fail('Неверный text');
                        return;
                    }
                    $selected += intval($value[$key]['selected']);
                    if (isset($condition['type'])) {
                        if ($condition['type'] !== $value[$key]['type']) {
                            $fail('Тип поля не совпадает');
                            return;
                        }
                        switch ($condition['type']) {
                            case 'files' :
                            {
                                foreach ($condition['items'] as $key2 => $item) {
                                    if (!isset($value[$key]['items'][$key2]['label']) || strcmp(trim($item['label']), trim($value[$key]['items'][$key2]['label'])) !== 0) {
                                        $fail('Неверный label');
                                        return;
                                    }
                                    foreach ($item['files'] as $v) {
                                        $file = app(FindFileByIdTask::class)->run($v);
                                        if (!isset($file) || !is_int($v) || $file->type !== 'qualification') {
                                            $fail('Прикреплен неверный файл');
                                            return;
                                        }
                                    }
                                }
                                break;
                            }
                            default :
                            {
                                $fail('Неверный тип поля');
                                return;
                            }
                        }
                    }
                }

                if ($selected === 0) {
                    $fail('Не выбрано соглашение!');
                }
            }],
        ];
    }

    public function isIndiv(): bool
    {
        return $this->profile()->hasLegalForm('indiv');
    }

    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return $this->check([
            'hasAccess',
            'profileIsAccredited',
            'isIndiv',
            'profileIsNotBanned',
            'userIsNotBanned'
        ]);
    }
}
